// 用户角色管理模块
class UserRoleManager {
    // 静态角色数据
    static roles = [
        { id: 1, name: '管理员', code: 'admin', description: '系统最高权限，可管理所有功能和用户', userCount: 5, status: 'active' },
        { id: 2, name: '教师', code: 'teacher', description: '可管理课程、查看学员信息、发布作业', userCount: 24, status: 'active' },
        { id: 3, name: '学员', code: 'student', description: '可查看课程、完成作业、查看个人成绩', userCount: 356, status: 'active' }
    ];
    
    // 获取所有角色
    static getAllRoles() {
        return [...this.roles];
    }
    
    // 根据ID获取角色
    static getRoleById(id) {
        return this.roles.find(role => role.id === id);
    }
    
    // 根据代码获取角色
    static getRoleByCode(code) {
        return this.roles.find(role => role.code === code);
    }
    static loadContent(container) {
        container.innerHTML = `
            <div class="description">
                配置系统中的用户角色，定义不同角色的权限和功能访问范围。
            </div>

            <div class="actions">
                <button class="btn btn-primary btn-add-role"><i class="fas fa-plus"></i> 新增角色</button>
                <button class="btn btn-default btn-edit-role-batch"><i class="fas fa-edit"></i> 修改角色</button>
                <button class="btn btn-danger btn-delete-role-batch"><i class="fas fa-trash"></i> 删除角色</button>
                <div class="search-area">
                    <input type="text" id="search-role-input" placeholder="搜索角色名称...">
                    <button id="search-role-btn" class="btn btn-primary"><i class="fas fa-search"></i> 搜索</button>
                </div>
            </div>
            
            <div class="table-container">
                <table>
                    <thead>
                        <tr>
                            <th><input type="checkbox" id="selectAllRoles"></th>
                            <th>角色名称</th>
                            <th>角色代码</th>
                            <th>描述</th>
                            <th>用户数量</th>
                            <th>状态</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody>
                        ${UserRoleManager.roles.map(role => `
                        <tr>
                            <td><input type="checkbox" class="rowCheckbox" data-id="${role.id}"></td>
                            <td>${role.name}</td>
                            <td>${role.code}</td>
                            <td>${role.description}</td>
                            <td>${role.userCount}</td>
                            <td><button class="status-btn ${role.status === 'active' ? 'active' : ''}">${role.status === 'active' ? '启用' : '禁用'}</button></td>
                            <td class="operation">
                                <a href="#" class="btn-edit-role" data-id="${role.id}"><i class="fas fa-edit"></i> 编辑</a>
                                <a href="#" class="btn-delete-role" data-id="${role.id}"><i class="fas fa-trash"></i> 删除</a>
                            </td>
                        </tr>`).join('')}
                    </tbody>
                </table>
            </div>
            
            <div class="pagination">
                <a href="#">上一页</a>
                <a href="#" class="active">1</a>
                <a href="#">2</a>
                <a href="#">3</a>
                <a href="#">4</a>
                <a href="#">5</a>
                <a href="#">下一页</a>
            </div>
        `;
        
        // 设置全选功能
        mainManager.setupSelectAll('selectAllRoles', 'rowCheckbox');

        // 设置操作按钮事件
        systemManager.setupActionButtons(container);

        // 绑定新增角色按钮事件
        const addRoleBtn = container.querySelector('.btn-add-role');
        if (addRoleBtn) {
            addRoleBtn.addEventListener('click', AddRoleModal.showModal);
        }

        // 设置搜索功能
        const searchBtn = container.querySelector('#search-role-btn');
        const searchInput = container.querySelector('#search-role-input');

        // 执行搜索的函数
        const executeSearch = () => {
            const keyword = searchInput.value.trim();
            if (!keyword) {
                alert('请输入搜索关键词');
                return;
            }
            UserRoleManager.performSearch(keyword, container);
        };

        // 搜索按钮点击事件
        if (searchBtn) {
            searchBtn.addEventListener('click', executeSearch);
        }

        // 输入框支持回车搜索
        if (searchInput) {
            searchInput.addEventListener('keypress', (e) => {
                if (e.key === 'Enter') {
                    executeSearch();
                }
            });
        }

        // 为编辑按钮添加点击事件（使用事件委托）
        const tableBody = container.querySelector('.table-container tbody');
        if (tableBody) {
            tableBody.addEventListener('click', (e) => {
                // 检查点击的是否是编辑按钮
                const editButton = e.target.closest('.btn-edit-role');
                if (editButton) {
                    e.preventDefault();
                    const roleId = parseInt(editButton.dataset.id);
                    const roleData = UserRoleManager.getRoleById(roleId);
                    if (roleData) {
                        EditRoleModal.showModal(roleData);
                    }
                }

                // 检查点击的是否是删除按钮
                const deleteButton = e.target.closest('.btn-delete-role');
                if (deleteButton) {
                    e.preventDefault();
                    const roleId = parseInt(deleteButton.dataset.id);
                    UserRoleManager.deleteRole(roleId, container);
                }
            });
        }
    }

    // 删除角色
    static deleteRole(roleId, container) {
        const role = UserRoleManager.getRoleById(roleId);
        if (!role) {
            alert('角色不存在');
            return;
        }

        this.showDeleteConfirm(role.name, () => {
            const index = UserRoleManager.roles.findIndex(r => r.id === roleId);
            if (index !== -1) {
                UserRoleManager.roles.splice(index, 1);
                alert('删除成功');
                UserRoleManager.loadContent(container);
            }
        });
    }

    // 显示删除确认弹窗
    static showDeleteConfirm(roleName, onConfirm) {
        const modal = document.createElement('div');
        modal.className = 'modal';
        modal.innerHTML = `
            <div class="modal-overlay"></div>
            <div class="modal-content" style="max-width: 400px;">
                <div class="modal-header">
                    <h3>删除确认</h3>
                    <button class="modal-close-btn"><i class="fas fa-times"></i></button>
                </div>
                <div style="padding: 20px; font-size: 16px; color: #333;">
                    确定要删除角色"${roleName}"吗？
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" id="delete-cancel-btn">取消</button>
                    <button type="button" class="btn btn-danger" id="delete-confirm-btn">确认删除</button>
                </div>
            </div>
        `;
        document.body.appendChild(modal);

        const closeBtn = modal.querySelector('.modal-close-btn');
        const cancelBtn = modal.querySelector('#delete-cancel-btn');
        const confirmBtn = modal.querySelector('#delete-confirm-btn');
        const overlay = modal.querySelector('.modal-overlay');

        const closeModal = () => {
            modal.classList.remove('show');
            setTimeout(() => modal.remove(), 300);
        };

        closeBtn.addEventListener('click', closeModal);
        cancelBtn.addEventListener('click', closeModal);
        overlay.addEventListener('click', closeModal);
        confirmBtn.addEventListener('click', () => {
            onConfirm();
            closeModal();
        });

        document.addEventListener('keydown', (e) => {
            if (e.key === 'Escape') closeModal();
        });

        setTimeout(() => modal.classList.add('show'), 10);
    }

    // 执行搜索功能
    static performSearch(keyword, container) {
        const tableBody = container.querySelector('.table-container tbody');
        if (!tableBody) return;

        const rows = tableBody.querySelectorAll('tr');
        let foundCount = 0;
        const keywordLower = keyword.toLowerCase();

        rows.forEach(row => {
            const nameCell = row.cells[1];
            const codeCell = row.cells[2];
            const descCell = row.cells[3];

            let matchFound = false;
            if (nameCell && codeCell && descCell) {
                const nameText = nameCell.textContent.toLowerCase();
                const codeText = codeCell.textContent.toLowerCase();
                const descText = descCell.textContent.toLowerCase();
                matchFound = nameText.includes(keywordLower) ||
                            codeText.includes(keywordLower) ||
                            descText.includes(keywordLower);
            }

            if (matchFound) {
                row.style.display = '';
                foundCount++;
            } else {
                row.style.display = 'none';
            }
        });

        if (foundCount === 0) {
            alert('未找到匹配的记录');
        }
    }
}

// 新增角色模态框
class AddRoleModal {
    static showModal() {
        const modal = document.createElement('div');
        modal.className = 'modal';
        modal.id = 'addRoleModal';

        modal.innerHTML = `
            <div class="modal-overlay"></div>
            <div class="modal-content">
                <div class="modal-header">
                    <h3>新增角色</h3>
                    <button class="modal-close-btn"><i class="fas fa-times"></i></button>
                </div>
                <form class="add-role-form">
                    <div class="form-group">
                        <label for="role-name">角色名称</label>
                        <input type="text" id="role-name" name="name" class="form-control" placeholder="2-20个字符" required>
                        <div class="error-text" id="role-name-error"></div>
                    </div>
                    <div class="form-group">
                        <label for="role-code">角色代码</label>
                        <input type="text" id="role-code" name="code" class="form-control" placeholder="字母、数字、下划线" required>
                        <div class="error-text" id="role-code-error"></div>
                    </div>
                    <div class="form-group">
                        <label for="role-description">描述</label>
                        <textarea id="role-description" name="description" class="form-control" placeholder="角色描述" rows="3" required></textarea>
                        <div class="error-text" id="role-description-error"></div>
                    </div>
                    <div class="form-group">
                        <label id="role-status-label">状态</label>
                        <div class="custom-radio-group" role="radiogroup" aria-labelledby="role-status-label" style="display: flex; gap: 20px;">
                            <div class="radio-option" style="display: flex; align-items: center;">
                                <input type="radio" id="role-status-active" name="status" value="active" checked>
                                <label for="role-status-active" style="margin-bottom: 0; margin-left: 8px;">启用</label>
                            </div>
                            <div class="radio-option" style="display: flex; align-items: center;">
                                <input type="radio" id="role-status-inactive" name="status" value="inactive">
                                <label for="role-status-inactive" style="margin-bottom: 0; margin-left: 8px;">禁用</label>
                            </div>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-default" id="role-cancel-btn">取消</button>
                        <button type="submit" class="btn btn-primary" id="role-save-btn" disabled>保存</button>
                    </div>
                </form>
            </div>
        `;

        document.body.appendChild(modal);
        AddRoleModal.initEvents();
        modal.classList.add('show');
    }

    static initEvents() {
        const modal = document.getElementById('addRoleModal');
        const closeBtn = modal.querySelector('.modal-close-btn');
        const cancelBtn = document.getElementById('role-cancel-btn');
        const form = modal.querySelector('.add-role-form');

        closeBtn.addEventListener('click', AddRoleModal.closeModal);
        cancelBtn.addEventListener('click', AddRoleModal.closeModal);
        modal.querySelector('.modal-overlay').addEventListener('click', AddRoleModal.closeModal);

        document.addEventListener('keydown', function(e) {
            if (e.key === 'Escape' && modal.classList.contains('show')) {
                AddRoleModal.closeModal();
            }
        });

        // 表单验证
        const fields = ['role-name', 'role-code', 'role-description'];
        fields.forEach(field => {
            const input = document.getElementById(field);
            input.addEventListener('input', () => {
                AddRoleModal.validateField(field, input.value);
                AddRoleModal.checkFormValidity(form);
            });
        });

        form.addEventListener('submit', function(e) {
            e.preventDefault();
            AddRoleModal.submitForm(form);
        });
    }

    static validateField(field, value) {
        let isValid = true;
        let errorMessage = '';

        switch (field) {
            case 'role-name':
                if (!value.trim()) {
                    errorMessage = '角色名称不能为空';
                    isValid = false;
                } else if (value.length < 2 || value.length > 20) {
                    errorMessage = '角色名称长度为2-20个字符';
                    isValid = false;
                }
                break;

            case 'role-code':
                const codeRegex = /^[a-zA-Z0-9_]+$/;
                if (!value.trim()) {
                    errorMessage = '角色代码不能为空';
                    isValid = false;
                } else if (!codeRegex.test(value)) {
                    errorMessage = '角色代码只能包含字母、数字和下划线';
                    isValid = false;
                }
                break;

            case 'role-description':
                if (!value.trim()) {
                    errorMessage = '描述不能为空';
                    isValid = false;
                }
                break;
        }

        const errorElement = document.getElementById(`${field}-error`);
        if (errorElement) {
            errorElement.textContent = errorMessage;
            errorElement.style.display = errorMessage ? 'block' : 'none';
        }

        const inputElement = document.getElementById(field);
        if (inputElement) {
            if (isValid) {
                inputElement.classList.remove('is-invalid');
                inputElement.classList.add('is-valid');
            } else {
                inputElement.classList.remove('is-valid');
                inputElement.classList.add('is-invalid');
            }
        }

        return isValid;
    }

    static checkFormValidity(form) {
        const saveBtn = document.getElementById('role-save-btn');
        const nameValid = AddRoleModal.validateField('role-name', form['name'].value);
        const codeValid = AddRoleModal.validateField('role-code', form['code'].value);
        const descValid = AddRoleModal.validateField('role-description', form['description'].value);

        saveBtn.disabled = !(nameValid && codeValid && descValid);
    }

    static submitForm(form) {
        const saveBtn = document.getElementById('role-save-btn');
        saveBtn.textContent = '保存中...';
        saveBtn.disabled = true;

        const formData = {
            id: UserRoleManager.roles.length + 1,
            name: form['name'].value,
            code: form['code'].value,
            description: form['description'].value,
            userCount: 0,
            status: form['status'].value
        };

        setTimeout(() => {
            UserRoleManager.roles.push(formData);
            alert('新增角色成功');
            AddRoleModal.closeModal();

            const container = document.getElementById('user-role');
            UserRoleManager.loadContent(container);
        }, 1000);
    }

    static closeModal() {
        const modal = document.getElementById('addRoleModal');
        if (modal) {
            modal.classList.remove('show');
            setTimeout(() => modal.remove(), 300);
        }
    }
}

// 修改角色模态框
class EditRoleModal {
    static showModal(roleData) {
        const modal = document.createElement('div');
        modal.className = 'modal';
        modal.id = 'editRoleModal';

        modal.innerHTML = `
            <div class="modal-overlay"></div>
            <div class="modal-content">
                <div class="modal-header">
                    <h3>修改角色</h3>
                    <button class="modal-close-btn"><i class="fas fa-times"></i></button>
                </div>
                <form class="edit-role-form">
                    <input type="hidden" id="edit-role-id" value="${roleData.id}">
                    <div class="form-group">
                        <label for="edit-role-name">角色名称</label>
                        <input type="text" id="edit-role-name" name="name" class="form-control" value="${roleData.name}" placeholder="2-20个字符" required>
                        <div class="error-text" id="edit-role-name-error"></div>
                    </div>
                    <div class="form-group">
                        <label for="edit-role-code">角色代码</label>
                        <input type="text" id="edit-role-code" name="code" class="form-control" value="${roleData.code}" placeholder="字母、数字、下划线" disabled>
                    </div>
                    <div class="form-group">
                        <label for="edit-role-description">描述</label>
                        <textarea id="edit-role-description" name="description" class="form-control" placeholder="角色描述" rows="3" required>${roleData.description}</textarea>
                        <div class="error-text" id="edit-role-description-error"></div>
                    </div>
                    <div class="form-group">
                        <label id="edit-role-status-label">状态</label>
                        <div class="custom-radio-group" role="radiogroup" aria-labelledby="edit-role-status-label" style="display: flex; gap: 20px;">
                            <div class="radio-option" style="display: flex; align-items: center;">
                                <input type="radio" id="edit-role-status-active" name="status" value="active" ${roleData.status === 'active' ? 'checked' : ''}>
                                <label for="edit-role-status-active" style="margin-bottom: 0; margin-left: 8px;">启用</label>
                            </div>
                            <div class="radio-option" style="display: flex; align-items: center;">
                                <input type="radio" id="edit-role-status-inactive" name="status" value="inactive" ${roleData.status === 'inactive' ? 'checked' : ''}>
                                <label for="edit-role-status-inactive" style="margin-bottom: 0; margin-left: 8px;">禁用</label>
                            </div>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-default" id="edit-role-cancel-btn">取消</button>
                        <button type="submit" class="btn btn-primary" id="edit-role-save-btn" disabled>保存</button>
                    </div>
                </form>
            </div>
        `;

        document.body.appendChild(modal);
        EditRoleModal.initEvents();
        modal.classList.add('show');
    }

    static initEvents() {
        const modal = document.getElementById('editRoleModal');
        const closeBtn = modal.querySelector('.modal-close-btn');
        const cancelBtn = document.getElementById('edit-role-cancel-btn');
        const form = modal.querySelector('.edit-role-form');

        closeBtn.addEventListener('click', EditRoleModal.closeModal);
        cancelBtn.addEventListener('click', EditRoleModal.closeModal);
        modal.querySelector('.modal-overlay').addEventListener('click', EditRoleModal.closeModal);

        document.addEventListener('keydown', function(e) {
            if (e.key === 'Escape' && modal.classList.contains('show')) {
                EditRoleModal.closeModal();
            }
        });

        // 表单验证
        const fields = ['edit-role-name', 'edit-role-description'];
        fields.forEach(field => {
            const input = document.getElementById(field);
            input.addEventListener('input', () => {
                EditRoleModal.validateField(field, input.value);
                EditRoleModal.checkFormValidity();
            });
        });

        // 初始验证
        EditRoleModal.validateField('edit-role-name', document.getElementById('edit-role-name').value);
        EditRoleModal.validateField('edit-role-description', document.getElementById('edit-role-description').value);
        EditRoleModal.checkFormValidity();

        form.addEventListener('submit', function(e) {
            e.preventDefault();
            EditRoleModal.submitForm(form);
        });
    }

    static validateField(field, value) {
        let isValid = true;
        let errorMessage = '';

        switch (field) {
            case 'edit-role-name':
                if (!value.trim()) {
                    errorMessage = '角色名称不能为空';
                    isValid = false;
                } else if (value.length < 2 || value.length > 20) {
                    errorMessage = '角色名称长度为2-20个字符';
                    isValid = false;
                }
                break;

            case 'edit-role-description':
                if (!value.trim()) {
                    errorMessage = '描述不能为空';
                    isValid = false;
                }
                break;
        }

        const errorElement = document.getElementById(`${field}-error`);
        if (errorElement) {
            errorElement.textContent = errorMessage;
            errorElement.style.display = errorMessage ? 'block' : 'none';
        }

        const inputElement = document.getElementById(field);
        if (inputElement) {
            if (isValid) {
                inputElement.classList.remove('is-invalid');
                inputElement.classList.add('is-valid');
            } else {
                inputElement.classList.remove('is-valid');
                inputElement.classList.add('is-invalid');
            }
        }

        return isValid;
    }

    static checkFormValidity() {
        const saveBtn = document.getElementById('edit-role-save-btn');
        const nameValid = EditRoleModal.validateField('edit-role-name', document.getElementById('edit-role-name').value);
        const descValid = EditRoleModal.validateField('edit-role-description', document.getElementById('edit-role-description').value);

        saveBtn.disabled = !(nameValid && descValid);
    }

    static submitForm(form) {
        const saveBtn = document.getElementById('edit-role-save-btn');
        saveBtn.textContent = '保存中...';
        saveBtn.disabled = true;

        const roleId = parseInt(document.getElementById('edit-role-id').value);
        const role = UserRoleManager.getRoleById(roleId);

        if (role) {
            role.name = form['name'].value;
            role.description = form['description'].value;
            role.status = form['status'].value;

            setTimeout(() => {
                alert('修改角色成功');
                EditRoleModal.closeModal();

                const container = document.getElementById('user-role');
                UserRoleManager.loadContent(container);
            }, 1000);
        }
    }

    static closeModal() {
        const modal = document.getElementById('editRoleModal');
        if (modal) {
            modal.classList.remove('show');
            setTimeout(() => modal.remove(), 300);
        }
    }
}